from google.appengine.api import users

import re

# TODO Document this
def buildLoginbarTemplateInputValues(requestHandler):
    # Creating an empty Template Input Values dictionary
    template_input_values = {}
    
    return fillLoginbarTemplateInputValues(requestHandler, template_input_values)

# TODO Document this
def fillLoginbarTemplateInputValues(requestHandler, dictionary):
    # Figuring Out if there is a User logged in or not
    if ( users.get_current_user() ):
        # Building User parameters
        dictionary['current_user'] = users.get_current_user()
        # Building Logout Link parameters
        dictionary['logout_link'] = users.create_logout_url( requestHandler.request.uri )
        dictionary['logout_link_text'] = 'Sign Out'
    else:
        # Building Login Link parameters
        dictionary['login_link'] = users.create_login_url( requestHandler.request.uri )
        dictionary['login_link_text'] = 'Sign In'
    
    return dictionary

# Check if the User has the Visibility Rights for the given List
def isListVisibileToUser(list, user):
    if ( list.visibility == 'private' and list.owner == user ):
        return True
    elif ( list.vibilility == 'shared' ) :
        return True # TODO - This needs to be Implemented
    elif ( list.visibility == 'public' ):
        return True
    else:
        return False

# Check that the User is the Owner of the given List
def isListOwnedByUser(list, user):
    if (list.owner == user):
        return True
    else:
        return False
     
# TODO Document this
def getBrowserDetails(userAgent):
   result = {}
   # Regexp for most used "User-Agent"s built using "http://www.useragentstring.com/"
   browsersRegexps = [
                      ['Internet Explorer', 'MSIE (\S+)'],
                      ['Opera', 'Opera[ /](\S+)'],
                      ['Konqueror', 'KHTML/(\S+)'],
                      ['Firefox', 'Gecko/\S+ Firefox/(\S+)'],
                      ['Chrome','AppleWebKit/\S+ (KHTML, like Gecko) Chrome/(\S+) Safari/\S+'],
                      ['Safari', 'Version/\S+ Safari/(\S+)'],
                      ['Mozilla', 'Gecko/(\S+)'],
                      ['WebKit', 'AppleWebKit/(\S+)']
                     ]
   
   # Search for the Browser that matches, if any
   for browser in browsersRegexps:
      compiledRegexp = re.compile( browser[1] )
      searchResult = compiledRegexp.search( userAgent )
      
      if (searchResult):
         result['browser_name'] = browser[0]
         result['browser_version'] = searchResult.group(1) 
         return result
   
   # If nothing matches, return "unknown"
   result['browser_name'] = "unknown"
   result['browser_version'] = "unknown" 
   return result
